<?php
declare(strict_types=1);
namespace app\admin\model;
use aphp\core\Model;

// 角色分组
class AdminGroup extends Model
{
    protected string $table = 'admin_group';
    protected string $pk = 'id';
    protected array $validate = [
        ['title', 'required', '角色名称不能为空', IF_ISSET, AC_BOTH],
        ['memo', 'required', '描述不能为空', IF_ISSET, AC_BOTH],
    ];
    protected array $auto = [
        ['status', 1, 'string', IF_MUST, AC_INSERT],
    ];

    protected function _before_insert(array &$data): void
    {
        $data['auth_node'] = !empty($data['auth_menu']) ? $this->_parse_auth_node($data['auth_menu']) : '';
    }

    protected function _before_update(array &$data): void
    {
        if (isset($data['edit_menu']) && !empty($data['auth_menu'])) {
            $auth_node = $this->_parse_auth_node($data['auth_menu']);
            if (empty($data['auth_node'])) {
                $data['auth_node'] = $auth_node;
            } else {
                $data['auth_node'] = ids_filter($data['auth_node'].','.$auth_node, false, false);
            }
        }
    }

    protected function _before_delete(array $data): void
    {
        $this->db = $this->db->where('id>1'); // 禁止删除超级管理
    }

    // 转换菜单权限到节点权限
    protected function _parse_auth_node(string $auth_menu = ''): string
    {
        $map = [];
        if (!empty($auth_menu)) {
            $map[] = ['id', 'in', $auth_menu];
        }
        $map[] = ['id>2 AND type=1 AND status=1'];
        $auth = db('menu')->where($map)->column('auth', 'id');
        $controller = array_map(fn(string $v): string => strstr($v, '/', true), $auth);
        $ids = db('auth_node')->where('controller', 'in', $controller)->where('method', 'index')->column('auth_id', 'id');
        $auth_node = '';
        if (!empty($ids)) {
            $ids = array_map(fn(int $n): int => -$n, $ids);
            foreach ($ids as $k => $v) {
                $auth_node .= $v . ','.$k.',';
            }
            $auth_node = rtrim($auth_node, ',');
        }
        return $auth_node;
    }
}